import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { AxiosService } from '../common/axios/axios.service';
import { ValidateDto } from './dto';
import * as crypto from 'crypto';

@Injectable()
export class CaptchaService {
  constructor(
    private readonly configService: ConfigService,
    private readonly axiosService: AxiosService,
  ) {}

  async validate(payload: ValidateDto) {
    const url = this.configService.get('captcha.geetest.host') + '/validate' + '?captcha_id=' + this.configService.get('captcha.geetest.id');
    const sign_token = crypto
      .createHmac('sha256', this.configService.get('captcha.geetest.key') as string)
      .update(payload.lot_number, 'utf8')
      .digest('hex');
    const submitData: {
      sign_token: string;
    } & ValidateDto = {
      sign_token,
      ...payload,
    };
    const res = await this.axiosService.post<{ result: string }>(url, submitData);
    const valid = res.data.result;
    if (valid !== 'success') {
      throw new HttpException('验证失败', HttpStatus.INTERNAL_SERVER_ERROR);
    }
    return res.data.result === 'success';
  }
}
